<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success">
      <el-step title="创建主题"></el-step>
      <el-step title="添加主体"></el-step>
      <el-step title="添加选项"></el-step>
      <el-step title="投票人"></el-step>
      <el-step title="投票结果可见范围"></el-step>
    </el-steps>

    <div class="subjectBuilder" v-if="active === 0">
      <el-form ref="form" :model="subjectForm" :rules="subjectRules" label-width="100px">
        <el-form-item label="主题名称" prop="description">
          <el-input v-model="subjectForm.description" placeholder="主题名称"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="subjectForm.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="cutOffTime">
          <el-date-picker
            v-model="subjectForm.cutOffTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="匿名投票">
          <el-switch
            v-model="subjectForm.anonymous">
          </el-switch>
        </el-form-item>
        <el-form-item label="主体乱序">
          <span slot="label">
                主体乱序
                <el-tooltip placement="top">
                  <div slot="content">
                    投票时显示的主体，是否打乱顺序，每个人看到的顺序均为随机排序。
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
          <el-switch
            v-model="subjectForm.randomOrder">
          </el-switch>
        </el-form-item>
        <el-form-item label="必填投票">
          <span slot="label">
                必填投票
                <el-tooltip placement="top">
                  <div slot="content">
                    是否必填，如果必填，则必须每个人都投完票后才结束投票，否则到截止时间，投票自动结束。
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
          <el-switch
            v-model="subjectForm.required">
          </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div class="principalBuilder" v-if="active === 1">
      <el-form :model="principalListForm" ref="principalListForm" :rules="principalRules" label-width="100px" class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in principalListForm.principalList"
          :label="'主体' + index"
          :key="domain.key"
          :prop="'principalList.' + index + '.description'"
          :rules="principalRules.description"
          >
          <el-row>
            <el-col :span="12">
              <el-input v-model="domain.description"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button   icon="el-icon-plus" circle @click.prevent="addDomain(domain)"></el-button>
              <el-button  icon="el-icon-minus" circle @click.prevent="removeDomain(domain)"></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <div class="optionBuilder" v-if="active === 2">
      <el-form :model="optionForm" ref="optionForm" label-width="90px" :rules="optionRules" class="demo-dynamic">
          <div class="option-score">
            <el-radio v-model="optionForm.optionType" label="0" border>使用选项</el-radio>
            <el-radio v-model="optionForm.optionType" label="1" border>使用分值</el-radio>
          </div>

        <div v-if="optionForm.optionType === '0'">
          <el-row v-for="(domain, index) in optionForm.optionList">
            <el-col :span="5">
              <el-form-item
                :label="'选项' + index +''"
                :key="domain.domKey"
                :prop="'optionList.' + index + '.description'"
                :rules="optionRules.description">
                <el-input v-model="domain.description"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                label="分值"
                :key="domain.key"
                :prop="'optionList.' + index + '.weightFactor'"
                :rules="optionRules.weightFactor">
                <el-input v-model.number="domain.weightFactor"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                label="最小个数"
                :key="domain.key"
                :prop="'optionList.' + index + '.minCount'"
                :rules="optionRules.minCount"
              >
                <el-input v-model.number="domain.minCount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                label="最大个数"
                :key="domain.key"
                :prop="'optionList.' + index + '.maxCount'"
                :rules="optionRules.maxCount"
               >
                <el-input v-model.number="domain.maxCount"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="3">
              <el-form-item
                label="默认"
                :key="domain.key"
                >
                <el-switch
                  v-model="domain.defaultOption"
                  @change="defaultSwitch($event, index)"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :key="domain.key">
              <el-button size="mini"  icon="el-icon-plus" circle @click.prevent="addOptionDomain(domain)"></el-button>
              <el-button size="mini" icon="el-icon-minus" circle @click.prevent="removeOptionDomain(domain)"></el-button>
              </el-form-item>
            </el-col>
          </el-row>

        </div>
        <div v-if="optionForm.optionType === '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="最小值"
                            prop="optionList.0.minScore"
                            :rules="optionRules.minScore"
              >
                <el-input v-model.number="optionForm.optionList[0].minScore"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大值"
                            prop="optionList.0.maxScore"
                            :rules="optionRules.maxScore"
                            >
                <el-input v-model.number="optionForm.optionList[0].maxScore"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div class="voterBuilder" v-if="active === 3">
      <el-form ref="voterForm" :model="voterForm" label-width="80px">
      <el-row>
      <el-col :span="24">
        <el-form-item label="投票人" prop="noticeUser">
          <el-tree
            :data="dUserTree"
            show-checkbox
            node-key="nodeId"
            ref="voteUserTree"
            :default-expanded-keys="expandedIds"
            :default-checked-keys="checkedIds"
            :props="defaultProps"
            @node-expand="nodeExpand"
            @node-collapse="nodeCollapse"
            @check-change="nodeCheck"
            key="voteUser"
          >
          </el-tree>
        </el-form-item>
      </el-col>
      </el-row>
      </el-form>
    </div>
    <div class="viewerBuilder" v-if="active === 4">
        <el-form ref="voterForm" :model="voterForm" label-width="80px">
          <el-row>
            <el-col :span="24">
<!--            <el-switch-->
<!--              v-model="viewScope"-->
<!--              active-text="投票人可见"-->
<!--              inactive-text="指定人可见"-->
<!--              class="option-score"-->
<!--              @change="changeOptionType"-->
<!--            />-->

              <div class = "option-score">
                <el-radio v-model="viewScope" :label="true" border>投票人可见</el-radio>
                <el-radio v-model="viewScope" :label="false" border>指定人可见</el-radio>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="!viewScope">
            <el-col :span="24">
              <el-form-item label="结果可见人员" prop="noticeUser">
                <el-tree
                  :data="dUserTree"
                  show-checkbox
                  node-key="nodeId"
                  ref="viewUserTree"
                  :default-expanded-keys="viewExpandedIds"
                  :default-checked-keys="viewCheckedIds"
                  :props="defaultProps"
                  @node-expand="nodeViewExpand"
                  @node-collapse="nodeViewCollapse"
                  @check-change="nodeViewCheck"
                  key="viewUser"
                >
                </el-tree>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
    </div>
    <el-button style="margin-top: 12px;" :disabled="stepNotPrev" @click="prev">上一步</el-button>
    <el-button style="margin-top: 12px;" :disabled="stepNotNext" @click="next">下一步</el-button>
    <el-button style="margin-top: 12px;" type="primary" v-if="showSubmit" @click="submitVote">{{submitButtonName}}</el-button>
  </div>
</template>

<script>
    import {deptUserFullTree} from "@/api/system/dept";
    import {submitVote, getSubjectGuideData } from "@/api/vote/vote";
    import { compareDate } from "@/utils/utils";

    export default {
      name: "VoteGuide",
      props: {
        subjectId: Number,
      },
      data() {
        let checkDuplicate = (rule, value, callback) => {
          let flag = false;
          for(let i = 0; i < this.principalListForm.principalList.length; i++) {
            if(this.principalListForm.principalList[i].description == value) {
              if(flag) {
                callback(new Error("主体信息重复"));
              } else {
                flag = true;
              }
            }
          }
          callback();
        };


        let checkOptionDuplicate = (rule, value, callback) => {
          let flag = false;
          for(let i = 0; i < this.optionForm.optionList.length; i++) {
            if(this.optionForm.optionList[i].description == value) {
              if(flag) {
                callback(new Error("主体信息重复"));
              } else {
                flag = true;
              }
            }
          }
          callback();

        };

        /**
         * 开始日期
         */
        let checkStartTime = (rule, value, callback) => {
          if(value) {
            if(!this.subjectForm.cutOffTime) {
              callback();
            } else {
              if (!compareDate(value, this.subjectForm.cutOffTime)) {
                callback(new Error("开始日期必须小于结束日期"));
              }else {
                callback();
              }
            }
          }else {
            callback();
          }

        };

        let checkCutOffTime = (rule, value, callback) => {
          if(value) {
            if(!compareDate(new Date(), value)) {
              callback(new Error("结束时间必须大于当前时间"));
            }

            if(!this.subjectForm.startTime) {
              callback();
            } else {
              if(!compareDate(this.subjectForm.startTime, value)) {
                callback(new Error("结束时间必须大于开始时间"))
              } else{
                callback();
              }
            }
          }
          callback();
        };

        let checkMaxCount = (rule, value, callback) => {

          if(!value) {
            callback();
          }else {
            if(value < 0) {
              callback(new Error("数量不可以小于0"))
            }
            let minCount = this.optionForm.optionList[this.getIndex(rule)].minCount;
            if(!minCount) {
              callback();
            }else {
              if(minCount > value) {
                callback("最大个数不得小于最小个数");
              }else {
                callback();
              }
            }

          }
        };

        let checkMinCount = (rule, value, callback) => {
          if(!value) {
            callback();
          }else {
            if(value < 0) {
              callback(new Error("数量不可以小于0"))
            }
            let maxCount = this.optionForm.optionList[this.getIndex(rule)].maxCount;
            if(!maxCount) {
              callback();
            }else {
              if(maxCount < value) {
                callback("最小个数不得小于最大个数");
              }else {
                callback();
              }
            }

          }
        };

        let checkMinScore = (rule, value, callback) => {
          console.log(rule)
          console.log(value)
          if(!value) {
            callback();
          }else {
            let maxScore = this.optionForm.optionList[this.getIndex(rule)].maxScore;
            console.log(this.getIndex(rule))
            console.log(maxScore)
            if(!maxScore) {
              callback();
            }else {
              if(maxScore < value) {
                callback("最小个数不得小于最大个数");
              }else {
                callback();
              }
            }
          }
        };
        let checkMaxScore = (rule, value, callback) => {
          if(!value) {
            callback();
          }else {
            let minScore = this.optionForm.optionList[this.getIndex(rule)].minScore;
            if(!minScore) {
              callback();
            }else {
              if(minScore > value) {
                callback("最小个数不得小于最大个数");
              }else {
                callback();
              }
            }
          }
        };
        return {
          active: 0,
          stepNotNext: false,
          stepNotPrev: true,
          subjectForm: {
            anonymous: true,
            randomOrder: true,
            required: true
          },
          subjectRules:{
            description: {
              required: true, message:'主题不可以为空', trigger:'blur'
            },
            startTime: {
              validator: checkStartTime
            },
            cutOffTime: {
              validator: checkCutOffTime
            }
          },
          // 主体
          principalListForm: {
            principalList: [{
              description: '',
              key: 0
          }]},
          principalRules: {
            description: [
              {required: true, message: '主体名不能为空', trigger: 'blur'},
              {validator: checkDuplicate}
            ]
          },

          // 选项
          optionForm: {
            optionType: '0',
            optionList: [{
              description: '',
              defaultOption: true,
              weightFactor: 1,
              maxCount: 1,
              minCount: 1,
              maxScore: 100,
              minScore: 0,
              domKey: 1
            }]
          },

          optionRules: {
            description: [
              {required: true, message: '选项名不能为空', trigger: 'blur'},
              {validator: checkOptionDuplicate}
            ],
            weightFactor: [
              {required: true, message: '权重不可以为空', trigger: 'blur'},
              {type: 'number',  message:'输入必须为数字', trigger:'blur'}
            ],
            maxCount:[
              {type: 'number',  message:'输入必须为数字', trigger:'blur'},
              {validator: checkMaxCount}
            ],
            minCount:[
              {type: 'number',  message:'输入必须为数字', trigger:'blur'},
              {validator: checkMinCount}
            ],
            minScore: [
              {type: 'number', message:'输入必须为数字', trigger:'blur'},
              {required:true, message:'最小分数不可以为空', trigger: 'blur'},
              {validator: checkMinScore}
            ],
            maxScore: [
              {type: 'number', message:'输入必须为数字', trigger:'blur'},
              {required:true, message:'最大分数不可以为空', trigger: 'blur'},
              {validator: checkMaxScore}
            ]
          },


          // 投票人
          defaultProps: {
            children: "children",
            label: "label",
            isLeaf: "leaf"
          },
          voteUserIds: [],
          voteDeptIds: [],
          // 查看人
          viewUserIds: [],
          viewDeptIds: [],

          checkedIds: [],
          expandedIds:[],
          dUserTree: [],
          voterForm: {},

          //可见范围
          viewScope: true,
          viewExpandedIds: [],
          viewCheckedIds:[],

        };
      },

      created() {
        this.reset();
        this.getDeptUserTree();
        this.getSubjectData(this.subjectId);
      },
      watch: {
        subjectId(value) {
          this.reset();
          this.getSubjectData(value);
        }
      },
      computed: {
        showSubmit() {
          return this.active === 4;
        },
        submitButtonName() {
          if(this.subjectId) {
            return "修改投票";
          }else {
            return "创建投票";
          }
        },
      },
      methods: {
        reset() {
          this.active = 0;
          this.stepNotNext = false;
          this.stepNotPrev = true;
          this.subjectForm = {
            anonymous: true,
            randomOrder: true,
            required: true,
            description: '',
            startTime: undefined,
            cutOffTime: undefined
          };

          this.principalListForm.principalList = [{
            description: '',
            key: 0
          }];

          this.optionForm = {
            optionType: '0',
            optionList: [{
              description: '',
              defaultOption: true,
              weightFactor: 1,
              maxCount: 1,
              minCount: 1,
              maxScore: 100,
              minScore: 0,
              domKey: 1
            }]
          };

          this.voteUserIds = [];
          this.voteDeptIds = [];
            // 查看人
          this.viewUserIds = [];
          this.viewDeptIds = [];

          this.checkedIds = [];
          this.expandedIds = [];
          this.voterForm = {};

          //可见范围
          this.viewScope = true;
          this.viewExpandedIds = [];
          this.viewCheckedIds = [];

        },

        next() {
          if(this.active == 0) {
            this.$refs["form"].validate(valid => {
              if (valid) {
                this.active = 1;
              }
            });
          }else if(this.active == 1) {
            if(this.principalListForm.principalList.length == 0) {
              this.principalListForm.principalList = [
                {description: '',
                  key: 0}
              ];
              this.msgError("请输入被投票主体");
              return;
            }
            this.$refs["principalListForm"].validate(valid => {
              if(valid) {
                this.active = 2;
              }
            })
          } else if(this.active == 2) {
            this.$refs["optionForm"].validate(valid => {
              if(valid) {
                this.active = 3;
              }
            })
          } else if(this.active == 3) {
            //投票人
            let voters = [];
            voters = this.$refs.voteUserTree.getCheckedNodes();
            if(voters.length === 0) {
              this.msgError("必须选择投票人");
              return;
            }
            for(let i = 0; i < voters.length; i++) {
              let key = voters[i];
              if(key.leaf) {
                this.voteUserIds.push(key.id);
              } else {
                this.voteDeptIds.push(key.id);
              }
            }
            if(this.voteUserIds.length == 0) {
              this.msgError("投票人不可以为空");
            }
            this.active = 4;
            this.stepNotNext = true;
          } else {
            // 4永不不会被点击了
          }

          this.stepNotPrev = false;
        },
        prev() {
          this.stepNotNext = false;
          if (--this.active <= 0) {
            this.stepNotPrev = true;

          }
        },
        removeDomain(item) {
          let index = this.principalListForm.principalList.indexOf(item)
          if (index !== -1) {
            this.principalListForm.principalList.splice(index, 1)
          }
        },
        addDomain(item) {
          let index = this.principalListForm.principalList.indexOf(item)
          if (index !== -1) {
            this.principalListForm.principalList.splice(index+1, 0, {
              description: '',
              key: Date.now()
            });
          }

        },


        removeOptionDomain(item) {
          let index = this.optionForm.optionList.indexOf(item)
          if (index !== -1) {
            this.optionForm.optionList.splice(index, 1)
          }
        },
        addOptionDomain(item) {
          let index = this.optionForm.optionList.indexOf(item)
          if (index !== -1) {
            this.optionForm.optionList.splice(index+1, 0, {
              description: '',
              defaultOption: false,
              weightFactor: 1,
              maxCount: 1,
              minCount: 1,
              domKey: Date.now()
            });
          }

        },
        changeOptionType(value) {
          console.log(value);
        },

        // 投票人
        /** 获取部门用户全量列表 */
        getDeptUserTree() {
          deptUserFullTree().then(response => {
            this.dUserTree = response.data;
          }).catch(e => {}) ;
        },

        /**
         * 获取主题数据
         */
        getSubjectData(subId) {
          if(subId == undefined) {
            return;
          }
          //获取subject数据
          getSubjectGuideData(subId).then(response => {
            let guide = response.data;

            this.subjectForm = guide.subject;
            this.principalListForm.principalList = guide.principalList;
            this.optionForm.optionType = guide.optionList[0].optionType;
            this.optionForm.optionList = guide.optionList;
            this.voteUserIds = guide.voteUserIds;
            this.viewUserIds = guide.viewUserIds;
            this.voteDeptIds = guide.voteDeptIds;
            this.viewDeptIds = guide.viewDeptIds;
            this.viewScope = guide.viewScope;

            if(this.voteDeptIds != undefined && this.voteDeptIds.length > 0) {
              for(let i = 0; i < this.voteDeptIds.length; i++) {
                this.expandedIds.push('dept-' + this.voteDeptIds[i]);
              }
            }
            if(this.voteUserIds != undefined && this.voteUserIds.length > 0) {
              for(let j = 0; j < this.voteUserIds.length; j++) {
                this.checkedIds.push("user-" + this.voteUserIds[j]);
              }
            }

            if(this.viewDeptIds != undefined && this.viewDeptIds.length > 0) {
              for(let i = 0; i < this.viewDeptIds.length; i++) {
                this.viewExpandedIds.push('dept-' + this.viewDeptIds[i]);
              }
            }
            if(this.viewUserIds != undefined && this.viewUserIds.length > 0) {
              for(let j = 0; j < this.viewUserIds.length; j++) {
                this.viewCheckedIds.push("user-" + this.viewUserIds[j]);
              }
            }
          })

        },
        /** 提交 */
        submitVote: function() {
          if(this.viewScope) {
            this.viewUserIds = this.voteUserIds;
            this.viewDeptIds = this.voteDeptIds;
          } else {
            let viewers = this.$refs.viewUserTree.getCheckedNodes();
            if(viewers.length === 0) {
              this.msgError("必须选择投票人");
              return;
            }
            for( let i = 0; i < viewers.length; i++) {
              let viewer = viewers[i];
              if(viewer.leaf) {
                this.viewUserIds.push(viewer.id);
              } else {
                this.viewDeptIds.push(viewer.id);
              }
            }
          }

          if (this.subjectId) {
            this.subjectForm.subjectId = this.subjectId;
          }
          submitVote(this.subjectForm, this.principalListForm,
            this.optionForm, this.voteUserIds, this.voteDeptIds,
            this.viewUserIds, this.viewDeptIds).then(response => {
              // 新增成功
            if (response.code === 200) {

              this.reset();
              this.$emit("on-result", true);
            } else {
              this.$emit("on-result", false);
            }
          })
        },

        nodeExpand(data) {
          this.expandedIds.push(data.nodeId); // 在节点展开是添加到默认展开数组
        },
        nodeCollapse(data) {
          this.expandedIds.splice(this.expandedIds.indexOf(data.nodeId), 1); // 收起时删除数组里对应选项
        },
        nodeCheck(data, checked) {
          if(checked) {
            this.checkedIds.push(data.nodeId)
          }else {
            this.checkedIds.splice(this.checkedIds.indexOf(data.nodeId), 1);
          }
        },
        nodeViewExpand(data) {
          this.viewExpandedIds.push(data.nodeId); // 在节点展开是添加到默认展开数组
        },
        nodeViewCollapse(data) {
          this.viewExpandedIds.splice(this.viewExpandedIds.indexOf(data.nodeId), 1); // 收起时删除数组里对应选项
        },
        nodeViewCheck(data, checked) {
          if(checked) {
            this.viewCheckedIds.push(data.nodeId)
          }else {
            this.viewCheckedIds.splice(this.viewCheckedIds.indexOf(data.nodeId), 1);
          }
        },

        getIndex(rule) {
          let field = rule.fullField;
          let temp = field.split(".")
          var index_str = temp[1];
          return parseInt(index_str);
        },

        defaultSwitch(e, i) {
          if( e == true) {
            let len = this.optionForm.optionList.length;
            for(let k = 0; k < len; k++) {
              if(k != i && this.optionForm.optionList[k].defaultOption) {
                this.optionForm.optionList[k].defaultOption = false;
              }
            }
          }
        }
      },


    }
</script>

<style scoped>
.option-score {
  margin-bottom: 10px;
  display: flex;
  justify-content: left;
}
</style>
